package com.rf.richfitwheel.workflow.service.impl;

import com.rf.richfitwheel.common.utils.UuidUtil;
import com.rf.richfitwheel.workflow.dao.WfAuthRuleMapper;
import com.rf.richfitwheel.workflow.model.*;
import com.rf.richfitwheel.workflow.service.WfAuthRuleService;
import com.rf.richfitwheel.workflow.service.WfStationProcessOrderService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("wfAuthRuleService")
public class WfAuthRuleServiceImpl implements WfAuthRuleService {

    @Autowired
    private WfAuthRuleMapper wfAuthRuleMapper;
    @Autowired
    private WfStationProcessOrderService wfStationProcessOrderService;

    @Override
    public List<WfAuthRule> listByStationProcessOrderId(String stationProcessOrderId) {
        WfAuthRuleExample example = new WfAuthRuleExample();
        WfAuthRuleExample.Criteria criteria = example.createCriteria();
        criteria.andStationProcessOrderIdEqualTo(stationProcessOrderId);
        List<WfAuthRule> list = wfAuthRuleMapper.selectByExample(example);
        return list;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(String folderCode, String stationProcessOrderId, String authType, JSONArray authRules) {
        wfStationProcessOrderService.updateAuthType(stationProcessOrderId, authType);
        this.deleteByProcessStationId(stationProcessOrderId);
        for (int i = 0; i < authRules.size(); i++) {
            JSONObject jsonObject = authRules.getJSONObject(i);
            WfAuthRule wfAuthRule = (WfAuthRule) JSONObject.toBean(jsonObject, WfAuthRule.class);
            wfAuthRule.setRuleType(authType);
            wfAuthRule.setStationProcessOrderId(stationProcessOrderId);
            this.save(wfAuthRule);
        }
    }

    @Override
    public void save(WfAuthRule wfAuthRule) {
        wfAuthRule.setId(UuidUtil.get32UUID());
        this.wfAuthRuleMapper.insert(wfAuthRule);
    }

    @Override
    public void deleteByProcessStationId(String stationProcessOrderId) {
        WfAuthRuleExample example = new WfAuthRuleExample();
        WfAuthRuleExample.Criteria criteria = example.createCriteria();
        criteria.andStationProcessOrderIdEqualTo(stationProcessOrderId);
        wfAuthRuleMapper.deleteByExample(example);
    }

    @Override
    public void deleteByIds(List<String> ids) {
        for (String id : ids) {
            wfAuthRuleMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public void deleteById(String id) {
        wfAuthRuleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(WfAuthRule wfAuthRule) {
        wfAuthRuleMapper.updateByPrimaryKey(wfAuthRule);
    }

}
